package concurrent;


import java.util.concurrent.Exchanger;

/**
 * @ClassName ExchangerExplore
 * @Description 用exchager来模拟两个小孩拍皮球的场景
 * @Author wanghaiwei
 * @Date 2022/2/21 17:27
 */
public class ExchangerExplore {
    Exchanger<Integer> passExchanger = new Exchanger<>();
    private volatile int i = 10;

    public class Summator implements Runnable{
        Integer num = 0;
        @Override
        public void run() {
            try {
                while (i > 0) {
                    if (num == 9) {
                        System.out.println("累加完成");
                        i--;
                        num = passExchanger.exchange(num);
                    } else {
                        num++;
                    }
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    public class Subtractor implements Runnable{
        Integer num = 9;
        @Override
        public void run() {
            try {
                while (i > 0) {
                    if (num == 0) {
                        System.out.println("减完了");
                        i--;
                        num = passExchanger.exchange(num);
                    } else {
                        num--;
                    }
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }


    public void tryPlay() {
        new Thread(new Summator()).start();
        new Thread(new Subtractor()).start();
    }

    public static void main(String[] args) {
        ExchangerExplore explore = new ExchangerExplore();
        explore.tryPlay();
    }
}
